package com.twang.stock.service;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.dto.ZuoYeSumbitDto;
import com.twang.stock.entity.*;
import com.twang.stock.mapper.ZuoYeRankMapper;
import com.twang.stock.mapper.ZuoYeSumbitMapper;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.utils.date.HolidayCopy;
import org.assertj.core.util.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class ZuoYeSumbitService {

    @Resource
    private ZuoYeSumbitMapper zuoYeSumbitMapper;

    @Resource
    private ZuoYeRankMapper zuoYeRankMapper;

    @Autowired
    private ZuoYeRankService zuoYeRankService;

    @Resource
    private CommonService commonService;

    public static String ZUO_YE_FIRST_SUMBIT="ZUO_YE_FIRST_SUMBIT";

    @Transactional(rollbackFor = Exception.class)
    public void saveData(ZuoYeSumbitDto zuoYeSumbitDto1) throws Exception {
        //当日记录
        ZuoYeSumbit zuoYeSumbit = insert(zuoYeSumbitDto1);
        //判断是否首日
        String openSwitch = commonService.getValue("ZUO_YE_FIRST_SUMBIT").toString();
        if (!"OPEN".equals(openSwitch)) {
            //更新资产收益率
            更新资产收益率(zuoYeSumbit);
        } else {
            ZuoYeRank zuoYeRank = new ZuoYeRank();
            zuoYeRank.setDate(zuoYeSumbit.getDate());
            zuoYeRank.setUserName(zuoYeSumbit.getName());
            zuoYeRank.setOrgAsset(zuoYeSumbit.getMoney());//最原始资产
            zuoYeRank.setInitialAsset(zuoYeSumbit.getMoney());//初始资产
            zuoYeRank.setTotalYield(BigDecimal.ZERO);//总收益
            zuoYeRank.setYesterdayAsset(BigDecimal.ZERO);//昨日总资产
            zuoYeRank.setYesterdayHold("首次报单");//昨日持仓
            zuoYeRank.setYesterdayYield(BigDecimal.ZERO);//昨日总收益
            zuoYeRank.setTodayAsset(zuoYeSumbit.getMoney());//最新市值
            zuoYeRank.setTodayHold(zuoYeSumbit.getStockDetail());//明细
            zuoYeRank.setTodayYield(BigDecimal.ZERO);
            zuoYeRank.setStatus("0");//状态：未更新
            zuoYeRank.setCreateTime(new Date());
            zuoYeRank.setUpdateTime(new Date());
            zuoYeRank.setIntegral(0);//积分
            zuoYeRankMapper.insert(zuoYeRank);
        }


    }

    /**
     * @param zuoYeSumbit
     * @throws Exception
     */
    public void 更新资产收益率(ZuoYeSumbit zuoYeSumbit) throws Exception {
        //先删除今天的，防止读到今天的
        zuoYeRankMapper.deletedData(zuoYeSumbit.getName(), zuoYeSumbit.getDate());
        //
        ZuoYeRank zuoYeRankResult = zuoYeRankMapper.queryuser(zuoYeSumbit.getName(), null);
        if (null == zuoYeRankResult) {
            log.error(">>>>>>>>>>>> 未查询到用户信息 name={} submitINfo={}", zuoYeSumbit.getName(), JSONObject.toJSONString(zuoYeSumbit));
            throw new Exception("未查询到用户信息，请联系大表哥!");
        }
        ZuoYeRank zuoYeRank = new ZuoYeRank();
        BeanUtils.copyProperties(zuoYeRankResult, zuoYeRank);
        if (null == zuoYeRank) {
            log.error(">>>>>>>>>>>> 未查询到用户信息 name={} submitINfo={}", zuoYeSumbit.getName(), JSONObject.toJSONString(zuoYeSumbit));
            throw new Exception("未查询到用户信息，请联系大表哥!");
        }

        if (zuoYeRank.getTodayAsset().compareTo(BigDecimal.ZERO) < 1) {
            zuoYeRank.setTodayAsset(zuoYeSumbit.getMoney());
        }
        BigDecimal 净资产 = (zuoYeRank.getTodayAsset()).divide(zuoYeRank.getInitialAsset(), BigDecimal.ROUND_HALF_DOWN, 2);

        zuoYeRank.setYesterdayAsset(zuoYeRank.getTodayAsset());
        zuoYeRank.setYesterdayYield(zuoYeRank.getTodayYield());
        zuoYeRank.setYesterdayHold(zuoYeRank.getTodayHold());
        //今日资产
        zuoYeRank.setTodayAsset(zuoYeSumbit.getMoney());
        //出入金
        BigDecimal hisOutInMoney = (null == zuoYeRank.getOutInMoney() ? BigDecimal.ZERO : zuoYeRank.getOutInMoney());
        BigDecimal outInMoney = (null == zuoYeSumbit.getOutMoney()) ? BigDecimal.ZERO : zuoYeSumbit.getOutMoney();
        zuoYeRank.setOutInMoney(hisOutInMoney.add(outInMoney));

        //今日初始资产
        BigDecimal 今日初始资产 = zuoYeRank.getInitialAsset().add(outInMoney.divide(净资产, BigDecimal.ROUND_HALF_DOWN, 2));
        zuoYeRank.setInitialAsset(今日初始资产);

        //今日收益率=（今日资产-昨日资产-今日出入金）/（昨日资产-今日出入金）
        BigDecimal todayYield = (zuoYeRank.getTodayAsset().subtract(zuoYeRank.getYesterdayAsset()).subtract(outInMoney)).divide(zuoYeRank.getYesterdayAsset().add(outInMoney), BigDecimal.ROUND_HALF_DOWN, 2);
        zuoYeRank.setTodayYield(todayYield);
        if (todayYield.compareTo(new BigDecimal(0.0002)) > 0) {
            zuoYeRank.setIntegral(zuoYeRank.getIntegral() + 1);
        }
        //总收益率
        BigDecimal 今日累计收益率 = zuoYeRank.getTodayAsset().subtract(今日初始资产).divide(今日初始资产, BigDecimal.ROUND_HALF_DOWN, 2);
        zuoYeRank.setTotalYield(今日累计收益率);


        //今日持仓
        zuoYeRank.setTodayHold(zuoYeSumbit.getStockDetail());

        //
        zuoYeRank.setCreateTime(new Date());
        zuoYeRank.setUpdateTime(new Date());
        zuoYeRank.setDate(zuoYeSumbit.getDate());
        zuoYeRank.setStatus("0");
        zuoYeRank.setId(null);
        if("SG".equals(zuoYeSumbit.getType())){
            zuoYeRank.setCcImage(zuoYeSumbit.getCcmx());
            zuoYeRank.setZzImage(zuoYeSumbit.getZzjl());
        }
        //生成最新的
        zuoYeRankMapper.insert(zuoYeRank);
        //
        zuoYeRankResult.setStatus("1");
        zuoYeRankResult.setUpdateTime(new Date());
        zuoYeRankMapper.updateByPrimaryKey(zuoYeRankResult);
    }

    /**
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void importData() {
        ZuoYeSumbit param = new ZuoYeSumbit();
        param.setDate(HolidayCopy.getRealToday());
        param.setType("SG");
        List<ZuoYeSumbit> result = zuoYeSumbitMapper.select(param);

        List<ZuoYeSumbit> error = Lists.newArrayList();
        result.forEach(item -> {
            String userName = item.getName().trim().replace(" ", "").replace(" ", "");
            item.setName(userName.toUpperCase());
            zuoYeSumbitMapper.updateByPrimaryKey(item);
            try {
                更新资产收益率(item);
            } catch (Exception e) {
                log.error(">>>>>>>>> importData userName error: ", userName, e);
                error.add(item);
            }
        });

        log.info(">>>>>>>>> importData  error list: {}", JSONObject.toJSONString(error));
        //更新未报单数据
        List<String> dates = zuoYeRankMapper.queryLastDate();
        String dateTime = dates.get(dates.size() - 1);
        List<ZuoYeRank> zuoYeRanks = zuoYeRankMapper.queryTodayNotUpLoad(dates.get(dates.size() - 2));
        List<String> 未报单 = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(zuoYeRanks)) {
            zuoYeRanks.forEach(item -> {
                item.setTodayYield(new BigDecimal(-1));
                item.setTotalYield(new BigDecimal(-1));
                item.setStatus("0");
                item.setUpdateTime(new Date());
                item.setDate(dateTime);
                item.setId(null);
                item.setTodayHold("未报单");
                item.setIntegral(item.getIntegral());
                zuoYeRankMapper.deletedData(item.getUserName(), item.getDate());
                zuoYeRankMapper.insert(item);
                未报单.add(item.getUserName());
            });
        }
        log.info(">>>>>>>>> importData  更新未报单数据 list: {}", JSONObject.toJSONString(未报单));
        //重新排序
        zuoYeRankService.doRank();
    }
    /**
     *
     * @param zuoYeSumbitDto
     * @throws Exception
     */
    public ZuoYeSumbit insert(ZuoYeSumbitDto zuoYeSumbitDto) throws Exception {
        ZuoYeSumbit zuoYeSumbit = new ZuoYeSumbit();
        if (null == zuoYeSumbitDto) {
            throw new Exception("提交记录不可为空！");
        }
        //用户名称
        if (StringUtils.isEmpty(zuoYeSumbitDto.getName())) {
            throw new Exception("用户名称不可为空！！");
        }
        String userName = zuoYeSumbitDto.getName().trim().replace(" ", "").replace(" ", "");
        zuoYeSumbit.setName(userName);

        //持仓市值
        if (StringUtils.isEmpty(zuoYeSumbitDto.getMoney())) {
            throw new Exception("持仓市值不可为空！！");
        }
        zuoYeSumbit.setMoney(new BigDecimal(zuoYeSumbitDto.getMoney()));

        zuoYeSumbit.setStockDetail(zuoYeSumbitDto.getStockDetail());

        zuoYeSumbit.setCcmx(zuoYeSumbitDto.getCcmx());

        //转出金额
        if (StringUtils.isNotEmpty(zuoYeSumbitDto.getOutMoney())) {
            BigDecimal outMoney = BigDecimal.ZERO;
            try {
                outMoney = new BigDecimal(zuoYeSumbitDto.getOutMoney());
            } catch (Exception e) {
                throw new Exception("转出金额,只允许输入数字！");
            }
            zuoYeSumbit.setOutMoney(outMoney);
            //转出明细截图
            if (StringUtils.isEmpty(zuoYeSumbitDto.getZzjl())) {
                // throw new Exception("您有转出金额，请提供转出明细截图，谢谢！");
            }
            zuoYeSumbit.setZzjl(zuoYeSumbitDto.getZzjl());
        }
        zuoYeSumbit.setDate(HolidayCopy.getRealToday());
        zuoYeSumbit.setCreateTime(new Date());
        zuoYeSumbit.setUpdateTime(new Date());
        ZuoYeSumbit param = new ZuoYeSumbit();
        param.setName(zuoYeSumbit.getName());
        param.setDate(zuoYeSumbit.getDate());
        zuoYeSumbitMapper.deletedData(zuoYeSumbit.getName(), zuoYeSumbit.getDate());
        zuoYeRankMapper.deletedData(zuoYeSumbit.getName(), zuoYeSumbit.getDate());
        zuoYeSumbitMapper.insert(zuoYeSumbit);
        return zuoYeSumbit;
    }
}
